package jdktcp.server;

import org.apache.commons.io.IOUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class JDKServer05ConnectionResetByPeer {

    static ExecutorService pool = Executors.newFixedThreadPool(100);

    public JDKServer05ConnectionResetByPeer() throws Exception {
        ServerSocket server = new ServerSocket(9999);
        System.out.println("init server :" + server);
        while (true) {
            Socket socket = server.accept();
            System.out.println("--->"+socket);
            execute(socket);
        }
    }

    private void execute(Socket socket) {
        pool.submit(() -> {
            try {
                byte[] buff = new byte[1024];
                InputStream in = socket.getInputStream();
                in.read(buff);
                System.out.println("revice==>" + new String(buff).trim());

                OutputStream out = socket.getOutputStream();

                //FIX 如果发送响应前应用程序退出但没有close socket,
                TimeUnit.MILLISECONDS.sleep(5000);
                //在此之前强行关闭客户端 socketTool
                out.write("nihao client".getBytes()); //此行write出现异常,会出现Connection reset by peer: socket write error
                System.out.println("send resp finish <---");
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                IOUtils.closeQuietly(socket);
            }
        });
    }

    public static void main(String[] args) throws Exception {
        new JDKServer05ConnectionResetByPeer();
    }
}
